<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;

use think\exception\ValidateException;
use think\facade\Log;

use util\Excel;
use think\facade\Db;
use think\cache\driver\Redis;

use util\Token;

use util\Upload;
/**
 * Querypurchase控制器
 */
class Querypurchaselast extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\ProcurementCostlast();

        $this->validate = \app\admin\validate\Querypurchase::class;
    }

    /**
     * 列表
     */
    public function index()
    {
        $redis = new Redis();
        $new_sku = $redis->get('querypurchaselast');
        if(empty($new_sku)){
            $thismonth=date('m');
            $thisyear=date('Y');
            if($thismonth==1){
                $lastmonth=12;
                $lastyear=$thisyear-1;
            }else{
                $lastmonth=$thismonth-1;
                $lastyear=$thisyear;
            }
            $lastStartDay=$lastyear.'-'.$lastmonth.'-1';
            $start_time=strtotime($lastStartDay);//上个月的月初时间戳
            $end_time=time();
    
            $sql = "
            SELECT 
            p.handle_url,
            b.sku
            FROM qu_order as a
            LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
            LEFT JOIN qu_order_product as p ON b.product_id=p.product_id
            where 
            a.created_at >= ".$start_time."
            AND a.created_at <= ".$end_time."
            AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
            AND a.status = 'normal'
            AND a.ismaterial = '2'
            GROUP BY b.sku
            ORDER BY b.sku desc";
            $list = Db::query($sql);
            if(!empty($list)){
                $new_sku = array();
                foreach ($list as $k=>$v) {
                    if(!empty($v['sku'])){
                        $pos = strpos($v['sku'], '-');
                        if($pos !== false){
                            $sku = explode('-',$v['sku']);
                            $sku0 = $sku[0];
                            $new_sku[$sku0] = $v;
                        }
                    }
                }
            }
            $redis->set('querypurchaselast', $new_sku, 60*60);
        }
        
        $new_sku3 = array();
        $new_num = 0;
        if(!empty($new_sku)){
            foreach ($new_sku as $k=>$v) {
                $procurement = table('procurement_cost')
                    ->where('number',$k)
                    ->find();
                if(!empty($procurement)){
                    if((float)$procurement['material'] > (float)0.001){
                        continue;
                    }
                }
                $procurement_cost = table('procurement_cost_last')
                    ->where('number',$k)
                    ->find();
                $new_sku2 = array();
                $new_sku2['number'] = $k;
                $new_sku2['material'] = 0;
                $new_sku2['handle_url'] = $v['handle_url'];

                if(empty($procurement_cost)){
                    $insert = array();
                    $insert['number'] = $k;
                    $insert['material'] = 0;
                    $insert['add_time'] = time();
                    $new_sku2['id'] = table('procurement_cost_last')->insertGetId($insert);$new_sku3[] = $new_sku2;
                    $new_num += 1;
                }else{
                    $new_sku2['id'] = $procurement_cost['id'];
                    $new_sku2['material'] = $procurement_cost['material'];
                    if((float)$procurement_cost['material'] < (float)0.001){
                        $new_sku3[] = $new_sku2;
                        $new_num += 1;
                    }
                }
            }
        }
        $list = $new_sku3;

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $new_num,
            'data' => $list,
        ];

        return json($data);
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id= input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if($post['material'] < 0.001){
                return error('采购成本为空');
            }
            try {
                $this->validate && validate($this->validate)->check($post);
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {

                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        return success('ok', $row);
    }

}
